package mychat.client;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;


public class Login{
	private JFrame frame;
	private JLabel l1=new JLabel();
	private JLabel l2=new JLabel("密    码:");
	private JTextField tf1=new JTextField();
	private JPasswordField tf2=new JPasswordField();
	private JButton b1=new JButton("登录");
	private JButton b2=new JButton("注册");
	private JButton b3=new JButton("关闭");
	private HandelAction handel=new HandelAction();
	public Login(){
		frame=new JFrame("Mychat Login");
		frame.setBounds(300, 250, 250, 150);
		l1.setText("用户名:");
		tf1.setColumns(15);
		tf2.setColumns(15);
		b1.addActionListener(handel);
		b2.addActionListener(handel);
		b3.addActionListener(handel);
		frame.getContentPane().setLayout(new FlowLayout());
		frame.getContentPane().add(l1);
		frame.getContentPane().add(tf1);
		frame.getContentPane().add(l2);
		frame.getContentPane().add(tf2);
		frame.getContentPane().add(b1);
		frame.getContentPane().add(b2);
		frame.getContentPane().add(b3);
		frame.setResizable(false);
		//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent arg0) {
				Client.cl.Close();
			}
			
		});
		frame.setVisible(true);
	}
	private boolean check(String user,String password){
		if(user==null || user.length()<4){
			JOptionPane.showMessageDialog(frame, "用户名长度不可能小于4，请得新输入！");
			return false;
		} else if(password == null || password.trim().equals("")){
			JOptionPane.showMessageDialog(frame, "密码不能为空，请得新输入！");
			return false;
		}
		return true;
	}
	private class HandelAction implements ActionListener {

		public void actionPerformed(ActionEvent e) {
				Object source=e.getSource();
				if(source==b3){
					Client.cl.Close();
				} else if(source==b2) {
					//frame.setVisible(false);
				} else {
					b1.setEnabled(false);
					String user=tf1.getText().trim();
					String pass=new String(tf2.getPassword());
					if (check(user,pass)) {
						String str=Client.cl.login(user,pass);
						if(null == str || str.equals("NO")){
							b1.setEnabled(true);
							tf2.setText("");
							JOptionPane.showMessageDialog(frame, "登录失败：\n用户名或密码错误！");
						} else if(str.equals("LOGIN")){
							b1.setEnabled(true);
							tf2.setText("");
							JOptionPane.showMessageDialog(frame, "登录失败：\n用户名已登录！");
						} else {
							frame.setVisible(false);
							Client.cl.start(str);
						}
					} 
				}
		}
		
	}
}
